package mood.su.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

import mood.su.data.DayMood;
import mood.su.data.Mood;

public class SqliteOpenHelper extends OrmLiteSqliteOpenHelper {
    private final String TAG = this.getClass().getSimpleName();
    /* declare entity class */
    private Class<?>[] classes = {Mood.class, DayMood.class};

    public SqliteOpenHelper(Context context) {
        super(context, DataFileConfig.getFilePath(), null, DataFileConfig.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource) {
        try {
            for (Class<?> clazz : classes) {
                TableUtils.createTableIfNotExists(connectionSource, clazz);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVer, int newVer) {
        try {
            for (Class<?> clazz : classes) {
                TableUtils.dropTable(connectionSource, clazz, true);
            }
            onCreate(database, connectionSource);
        } catch (SQLException e) {
            Log.e(TAG, "Unable to upgrade database from version " + oldVer
                    + " to new " + newVer, e);
            e.printStackTrace();
        }
    }
}
